﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectCloth.Entity;
using System.IO;
using ProjectCloth.FrmUI.Common;
using ProjectCloth.Entity.Enum;

namespace ProjectCloth.FrmUI
{
    public partial class SaleTable : UserControl
    {
        private ClothContext db = new ClothContext();
        public SaleTable()
        {
            InitializeComponent();
            companyCbb.DataSource = db.Companies.ToList();
            companyCbb.ValueMember = "Id";
            companyCbb.DisplayMember = "Name";
            companyCbb.SelectedValue = 0;
            outmoneycbb.DataSource = db.CashAccounts.ToList();
            outmoneycbb.DisplayMember = "TradeTypeName";
            outmoneycbb.ValueMember = "Id";
            outmoneycbb.SelectedValue = 0;
            var selectList = new List<DataItemStatus>();
            selectList.Add(new DataItemStatus()
            {
                Id = 0,
                Name = "未收款"
            });
            selectList.Add(new DataItemStatus()
            {
                Id = 1,
                Name = "已收款"
            });
            //selectList.Add(new DataItemStatus()
            //{
            //    Id = 2,
            //    Name = "作废"
            //});
            statusCombobox.DataSource = selectList;
            statusCombobox.DisplayMember = "Name";
            statusCombobox.ValueMember = "Id";
            statusCombobox.SelectedValue = -1;


        }
        public List<SaleTableModel> getSql()
        {
            var startTime = startDatePiker.Value.Date;
            var endTime = endDatePicker.Value.AddDays(1).Date;
            var instockNo = InstockNoTxt.Text != null ? InstockNoTxt.Text : "";
            var CompanyName = CompanyNameTxt.Text;
            var Phone = PhoneTxt.Text;
            var liaison = LiaisonTxt.Text;
            var isPay = statusCombobox.SelectedValue != null ? ((int)statusCombobox.SelectedValue == 0 ? false : true) : false;
            var selCompanyId = companyCbb.SelectedValue != null ? (int)companyCbb.SelectedValue : 0;
            var list = (from oi in db.SaleOrderItems//.ToList()
                        join o in db.SaleOrders on oi.OrderId equals o.Id
                        join s in db.InStockItems on oi.Id equals s.SaleOrderItemId into os
                        from osi in os.DefaultIfEmpty()
                        join pr in db.Products on oi.ProductId equals pr.Id
                        where o.RecordDate > startTime && o.RecordDate < endTime && o.OrderStatus != 2
                        && (string.IsNullOrEmpty(CompanyName) || o.CompanyName.Contains(CompanyName))
                        && (string.IsNullOrEmpty(Phone) || o.Phone.Contains(Phone))
                        && (string.IsNullOrEmpty(liaison) || o.Liaison.Contains(liaison))
                        && (string.IsNullOrEmpty(instockNo) || osi.InstockItemNo.Contains(instockNo))
                        && (string.IsNullOrEmpty(orderNoTxt.Text) || oi.OrderNo.Contains(orderNoTxt.Text))
                        && (string.IsNullOrEmpty(orderproductnoTxt.Text) || pr.ProductNo.Contains(orderproductnoTxt.Text))
                        && (string.IsNullOrEmpty(InstockproductTxt.Text) || osi.InstockProductName.Contains(InstockproductTxt.Text))
                        && (selCompanyId == 0 || osi.CompanyId == selCompanyId)
                        && (statusCombobox.SelectedValue == null || isPay == (o.OrderStatus == 0 ? false : true))
                        select new SaleTableModel
                        {
                            SaleColorType = oi.ColorType,
                            ColorType = osi.ColorType,
                            SaleOrderRemark = o.Remark,
                            Summary = o.Summary + "|" + o.CompanyName + "|" + o.Liaison + "|" + o.Phone,
                            Amount = oi.Amount,
                            Price = oi.Price,
                            SaleOrderNo = o.OrderNo,
                            saleProduct = pr.ProductNo,
                            Remark = o.Remark,
                            Time = o.RecordDate,
                            Status = o.OrderStatus.ToString(),
                            Id = o.Id,
                            SaleItemRemark = oi.Remark,
                            SaleQuantity = oi.Quantity,
                            CompanyName = osi.CompanyNo != null ? osi.CompanyNo : "",
                            InStockNo = osi.InstockItemNo != null ? osi.InstockItemNo : "",
                            InStockProductName = osi.InstockProductName != null ? osi.InstockProductName : "",
                            InstockPrice = osi.Price != null ? osi.Price : 0,
                            Quantity = osi.Quantity != null ? osi.Quantity : 0,
                            InstockAmount = osi.Amount != null ? osi.Amount : 0
                        }).ToList();
            foreach(var p in list)
            {
                var status = Convert.ToInt32(p.Status);
                p.Status = EnumDefine.GetEnumDescription((OrderStatus)status);
            }
            return list;
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            var list = getSql();
            dataGridView1.DataSource = list;
            quanlitySumTxt.Text = list.Sum(o => o.SaleQuantity).ToString();
            saleSumTxt.Text = list.Sum(o => o.Amount).ToString();
            instocksumTxt.Text = list.Sum(o => o.InstockAmount).ToString();
        }
        private void dataGdv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var dataGdv = dataGridView1;
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGdv.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGdv.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGdv.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void exportBtn_Click(object sender, EventArgs e)
        {
            Helper.ExportDgv(dataGridView1, "销售单大表格");
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {

                DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                if (column.Name == "SaleOrderNo")
                {
                    var orderNo = dataGridView1.CurrentRow.Cells["SaleOrderNo"].Value;
                    if (orderNo != null && (orderNo.ToString().StartsWith("J") || orderNo.ToString().StartsWith("D")))
                    {
                        var show = new SaleOrderShow(orderNo.ToString());
                        show.Show();
                    }
                }
                //else if (column.Name == "RelatedObject")
                //{
                //    var orderNo = dataGridView1.CurrentRow.Cells["RelatedObject"].Value;
                //    if (orderNo != null && (orderNo.ToString().StartsWith("J") || orderNo.ToString().StartsWith("D")))
                //    {
                //        var show = new SaleOrderShow(orderNo.ToString());
                //        show.Show();
                //    }
                //}

            }
        }

        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var sql = getSql();
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column != null)
            {
                var list = new List<SaleTableModel>();
                if (column.Name == "SaleOrderNo")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.SaleOrderNo).ToList();
                }
                else if (column.Name == "saleProduct")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.saleProduct).ToList();
                }
                else if (column.Name == "Time")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Time).ToList();
                }
                else if (column.Name == "SaleOrderRemark")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.SaleOrderRemark).ToList();
                }
                else if (column.Name == "Amount")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Amount).ToList();
                }
                else if (column.Name == "CompanyName")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.CompanyName).ToList();
                }
                else if (column.Name == "Quantity")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Quantity).ToList();
                }
                else if (column.Name == "Status")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Status).ToList();
                }
            }
        }

        private void dataGridView1_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var sql = getSql();
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column != null)
            {
                if (column.Name == "SaleOrderNo")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.SaleOrderNo).ToList();
                }
                else if (column.Name == "saleProduct")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.saleProduct).ToList();
                }
                else if (column.Name == "Time")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Time).ToList();
                }
                else if (column.Name == "SaleOrderRemark")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.SaleOrderRemark).ToList();
                }
                else if (column.Name == "Amount")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Amount).ToList();
                }
                else if (column.Name == "CompanyName")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.CompanyName).ToList();
                }
                else if (column.Name == "Quantity")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Quantity).ToList();
                }
                else if (column.Name == "Status")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Status).ToList();
                }
            }
        }

        private void GroupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
    public class SaleTableModel
    {
        public string SaleColorType { get; set; }
        public string ColorType { get; set; }
        public string SaleOrderRemark { get; set; }
        public string Summary { get; set; }
        public decimal Amount { get; set; }
        public decimal Price { get; set; }
        public string SaleOrderNo { get; set; }
        public string saleProduct { get; set; }
        public string Remark { get; set; }
        public DateTime Time { get; set; }
        public string Status { get; set; }
        public int Id { get; set; }
        public string SaleItemRemark { get; set; }
        public decimal SaleQuantity { get; set; }
        public string CompanyName { get; set; }
        public string InStockNo { get; set; }
        public string InStockProductName { get; set; }
        public decimal InstockPrice { get; set; }
        public decimal Quantity { get; set; }
        public decimal InstockAmount { get; set; }
    }
}
